<?php

namespace App\Jobs;

use App\Constant\QueueKey;
use App\Constant\ThirdMoneyCode;
use App\Facades\MoneyPlatformRequestFacade;
use App\Models\RepayRecord;
use App\Models\RepayRecordMoney;
use App\Models\RepaySummary;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Carbon;

class RepayJcfcSyncJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 任务最大尝试次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 任务运行的超时时间。
     *
     * @var int
     */
    public $timeout = 30; //秒数

    protected $record;
    /**
     * 创建一个新的任务实例。
     *
     * @param RepayRecord $record
     * @return void
     */
    public function __construct(RepayRecord $record)
    {
        $this->onQueue(QueueKey::QUEUE_REPAY_JINSHANG_SYNC);
        $this->record = $record;
    }

    /**
     * 运行任务。
     *
     * @throws \Exception
     * @return void
     */
    public function handle()
    {
        $summary=$this->record->relationSummary;
        $data1['loanId'] = $summary->loan_id;
        $data1['period'] = $this->record->period;
        $result = MoneyPlatformRequestFacade::getRepayPlan($data1);
        $data = isset($result['data']) ? $result['data'] : '';
        if(!empty($data)) {
            try {
                $is_success = RepayRecordMoney::getMoneyPlanStatus($data['status']);
                if($is_success) {
                    \DB::beginTransaction();
                    RepayRecordMoney::setMoneySuccessStatus($this->record->money,$data);
                    \DB::commit();
                    RepaySummary::setCurrentRepayJob($this->record,RepayRecord::REPAY_TYPE_AUTO);
                }
            }catch (\Exception $e) {
                \DB::rollBack();
                \Log::debug('jcfc_sync',['message' => '同步更新表数据失败，原因: '. $e->getMessage()]);
            }
        }
        $this->delete();
    }

}
